package com.example.service.impl;

import com.example.dao.UserDao;
import com.example.pojo.User;
import com.example.pojo.UserExample;
import com.example.pojo.PageBean;
import com.example.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public User login(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUnameEqualTo(user.getUname());
        criteria.andUpswEqualTo(user.getUpsw());
        List<User> userList = userDao.selectByExample(userExample);
        return userList.size()==0?null:userList.get(0);
    }
    @Override
    public List<User> getUserByPage(PageBean pageBean, User user) {

        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if(user.getUname()!=null&&!user.getUname().equals("")){
            criteria.andUnameLike("%"+user.getUname()+"%");
        }

        Long countRow = userDao.countByExample(userExample);
        pageBean.setCountRow(countRow.intValue());
        Integer countPage=pageBean.getCountRow()%pageBean.getPageSize()==0?pageBean.getCountRow()/pageBean.getPageSize():pageBean.getCountRow()/pageBean.getPageSize()+1;
        pageBean.setCountPage(countPage);

        userExample.setOffset((long)((pageBean.getCountPage()-1)*pageBean.getPageSize()));
        userExample.setLimit(pageBean.getPageSize());

        List<User> userList=userDao.selectByExample(userExample);
        return userList;
    }
    /*
     * 查找所有
     * */
    @Override
    public List<User> findAll() {
        List<User> userList = userDao.selectByExample(null);
        return userList;
    }
    /*
     * 重置密码
     * */
    @Override
    public void resetPsw(User user) {
        UserExample example = new UserExample();
        //生成8位数的随机uuid
        user.setUpsw(UUID.randomUUID().toString().substring(0,8));
        userDao.updateByPrimaryKey(user);
    }
    /*
     * 查一个
     * */
    @Override
    public User selectOne(Integer user_id) {
        User user = userDao.selectByPrimaryKey(user_id);
        return user;
    }

    @Override
    public void reg(User user) {
        userDao.insert(user);
    }

    @Override
    public Integer findOne(User user) {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (user.getUname() != null && !"".equals(user.getUname())){
            criteria.andUnameEqualTo(user.getUname());
        }
        List<User> userList = userDao.selectByExample(userExample);
        return userList.size();
    }


}
